<template>
  <div class="page bgc-fff">
    <!-- title -->
    <div class="title-wrap pad-t30 f16 c-333">
      司机注册
    </div>
    <!-- input查询 -->
    <div class='login-input-wrap'>
      <!-- <input type="hidden" name="_csrf" id="order_csrf" value="<?php //echo Yii::$app->request->csrfToken?>"/> -->
      <div class="login-input-box">
        <div class="input-cells a-between">
          <div class="flex l-center a-left">
            <div class="f-fl input-label w90">手机号码</div>
            <input type="tel" class=" cell-input w150" placeholder="请输入手机号码"
              style="text-align:left;" maxlength="11" v-model.trim="registParam.phone" @keyup = "phoneKeyup"/>
          </div>
          <img v-show="registParam.phone" class="icon-delete"
              :src="staticImgData.imgurla" alt="" @click="cleanInput('phone')">
        </div>
        <div class="input-cells a-between mt10">
          <div class="flex l-center a-left">
            <div class="f-fl input-label w90">登录密码</div>
            <input type="password" class=" cell-input w150"   placeholder="请输入6-20位密码"
              style="text-align:left;"  maxlength="18"  v-model.trim="registParam.password"  />
          </div>
          <img v-show="registParam.password" class="icon-delete"
              :src="staticImgData.imgurla" alt="" @click="cleanInput('password')">
        </div>
        <div class="input-cells a-between mt10">
          <div class="flex l-center a-left">
            <div class="f-fl input-label w90">确认密码</div>
            <input type="password" class=" cell-input w150"   placeholder="请再次确认密码" @blur="checkTwoPsw"
              style="text-align:left;" maxlength="18"  v-model.trim="registParam.passwords"  />
          </div>
          <img v-show="registParam.passwords" class="icon-delete"
              :src="staticImgData.imgurla" alt="" @click="cleanInput('passwords')">
        </div>
        <div class="input-cells a-between mt10">
          <div class="flex l-center a-left">
            <div class="f-fl input-label w90">公司名称</div>
            <input type="text" class=" cell-input w150"   placeholder="请输入公司名称"
              @focus="companyInputEnter()"  @blur="checkTwoPsw"
              style="text-align:left;" maxlength="20"  v-model.trim="companyKeyWord"  />
          </div>
          <img v-show="companyKeyWord" class="icon-delete"
              :src="staticImgData.imgurla" alt="" @click="cleanInput('companyKeyWord')">
        </div>
      </div>
      <div>
        <p class="large-btn" :disabled="disabled" :class="[{'bgc-7cbdff':!disabled}]" @click="subAxios">{{sub_btn_msg}}</p>
      </div>
      <div class="flex a-right l-center pad15">
        <span class="f12 c-01a4f6" @click="toLoginNormal">已有账号前往登录</span>
      </div>
    </div>

    <!-- picker -->
    <div class="down-picker-bg " :class="[{'down-picker-bg-up':downPickerShow}]" >
      <div class="down-picker-container" :class="[{'down-picker-container-up':downPickerShow}]">
        <div class="flex l-center a-between f14 bor-bottom bgc-fff pad15">
          <span @click="closeDownPicker()" class="c-999">取消</span>
          <span @click="closeDownPicker()" class="c-01a4f6" >确定</span>
        </div>
        <Picker :data='pickerData' v-model='pickerSelect' @on-change='placeChange'></Picker>
        <!-- 写法错误onValuesChange() <mt-picker :slots="slots"  @change="onValuesChange()"></mt-picker> -->
        <!--<mt-picker :slots="slots"  @change="onValuesChange"></mt-picker>-->
        <!--<div class="down-picker-btn-box"  @click="closeDownPicker()">-->
          <!--确定-->
        <!--</div>-->
      </div>
    </div>
     <!--loading  -->
    <v-loading  v-show="loadingShow" style="z-index:11" ></v-loading>
  </div>
</template>

<script type="text/ecmascript-6">
  import '@/styles/multiPicker.css'
  import '@/styles/downPicker.css'
  import Vue from 'vue'
  import Loading from '@/components/common/loading/loading.vue'
  import { Picker } from 'vux'
  import { Toast } from 'mint-ui'
  import Utils from '@/utils/util'
  import * as AccountApi from '@/api/account'
  Vue.component(Picker.name, Picker)
  export default {
    name: 'driver-signup',
    data() {
      return {
        nums: 15,
        staticImgData: {
          imgurla: require('@/assets/image/common/icon_delete.png')
        },
        registParam: {
          phone: '',
          password: '',
          companyName: '',
          passwords: ''
        },
        companyListData: [],
        companyKeyWord: '', // 公司名查询
        isHavePickerCompany: false, // 是否有选中
        downPickerShow: false,
        pickerData: [],
        pickerSelect: [],
        searchRun: false,
        companyPickerVal0: '',
        isOldvalHave: true,
        sub_btn_msg: '注册',
        loadingShow: false, // loading显隐
        disabled: true, // 登录禁止点击
        prevent_repeat: false,
        loadingFail: false
      }
    },
    components: {
      Picker,
      'v-loading': Loading
    },
    created() {
    },
    computed: {
      registParamCom() {
        const { phone, password, passwords } = this.registParam
        const companyName = this.companyKeyWord
        return {
          phone,
          password,
          companyName,
          passwords
        }
      }
    },
    watch: {
      registParamCom: {
        handler: function(newValData) {
          const that = this
          const vala = newValData.phone.length
          const valb = newValData.password
          const valc = newValData.passwords
          const vald = newValData.password.length
          const vale = newValData.passwords.length
          const valf = newValData.companyName
          if (vala === 11 && valb !== '' && valc !== '' && valb === valc && vald > 5 && vale > 5 && vald < 20 && vale < 20 && valf !== '') {
            that.disabled = false
          } else {
            that.disabled = true
          }
          if (vald > 20 && vale > 20) {
            Toast({
              message: '请输入6-20位的密码',
              duration: 1500
            })
          }
        },
        deep: true
      }
    },
    mounted() {
      this.$watch('companyKeyWord', (newVal, oldVal) => {
        if (this.searchRun) {
          // 当弹窗 选中值 关闭后 再重新开启 keyword查询
          let timer = null
          clearTimeout(timer)
          // 再次创建延时器
          const val = newVal
          if (this.isOldvalHave) {
            oldVal = '' // 防止初次 oldVal undefined报错
            this.isOldvalHave = false
          }
          if (val !== '' && newVal.length >= 1 && newVal.length > oldVal.length) {
            timer = setTimeout(() => {
              const req_params = {
                corpName: val
              }
              AccountApi.getListByCorpName(req_params).then(res => {
                if (res.status === 200) {
                  if (res.data.code === 0) {
                    this.companyListData = res.data.data
                    if (this.companyListData.length !== 0 && this.companyKeyWord !== '') {
                      this.showPickCity(this.companyListData)
                    }
                  } else {
                    Toast({
                      message: '查询无相关公司信息',
                      duration: 1000
                    })
                    setTimeout(() => {
                      this.companyKeyWord = ''
                      this.registParam.companyName = ''
                    }, 1000)
                    return
                  }
                }
              }).catch(res => {
                // 整个请求失败
                Toast({
                  message: '查询无相关公司信息',
                  duration: 1000
                })
                setTimeout(() => {
                  this.companyKeyWord = ''
                  this.registParam.companyName = ''
                }, 1000)
                console.log('error', res)
              })
            }, 1200)
          } else {
            console.log('正在手动清除输入值')
            this.companyKeyWord = ''
            this.registParam.companyName = ''
          }
          if (val === '') {
            this.companyKeyWord = ''
            this.registParam.companyName = ''
          }
        }
      })
    },
    methods: {
      cleanInput: function(val) {
        const res_val = val
        if (res_val === 'phone') {
          this.registParam.phone = ''
        } else if (res_val === 'password') {
          this.registParam.password = ''
        } else if (res_val === 'passwords') {
          this.registParam.passwords = ''
        } else if (res_val === 'companyKeyWord') {
          this.companyKeyWord = ''
          this.registParam.companyName = ''
        }
      },
      companyInputEnter: function() {
        this.searchRun = true
      },
      // cityPicker 用户有移动选项时 才触发 取值
      placeChange: function(values) {
        // 有 进入picker 滑动picker选了值 values[0]有值 后续才给赋值
        const res_val = values
        if (res_val) {
          this.isHavePickerCompany = true
          this.companyPickerVal0 = values[0]
        }
      },
      // 展示 cityPicker
      showPickCity: function(listdata) {
        const that = this
        const new_resData = listdata
        const showPickList2 = []
        if (new_resData.length !== 0) {
          for (let i = 0; i < new_resData.length; i++) {
            // 防止 corpName 为null 时候报错
            if (new_resData[i].corpName) {
              showPickList2.push(new_resData[i].corpName)
              // 如果值填完了 就开启 picker组件
              if (i === (new_resData.length - 1)) {
                // that.slots = [{ values: showPickList2 }]
                this.pickerData = []
                this.pickerData.push(showPickList2)
                // 如果 keyword查询出 数据，则开启 picker组件 并且开启 keword 热搜索
                if (this.companyListData.length !== 0) {
                  that.searchRun = false
                  that.downPickerShow = true
                }
              }
            }
          }
        }
      },
      // 关闭 cityPiker 主要用于 多选
      closeDownPicker: function() {
        const that = this
        that.downPickerShow = false
        const mapData = this.companyListData
        // 有 进入picker 滑动picker选了 值 才给赋值
        if (this.isHavePickerCompany) {
          if (this.companyPickerVal0) {
            for (const k in mapData) {
              const map_item = mapData[k]
              if (map_item.corpName === this.companyPickerVal0) {
                this.registParam.companyName = map_item.id
                this.companyKeyWord = this.companyPickerVal0
              }
            }
          }
        }
        that.searchRun = false
      },
      phoneKeyup: function() { // 电话号码输入框
        const key = this.registParam.phone.length
        if (key === 11) {
          this.code_prevent = false
          this.telFormatting(this.registParam.phone)
        }
      },
      telFormatting: function(param) { // 电话号码格式化
        let num = this.registParam.phone
        let num_ = this.registParam.phone
        num = num.replace(/\s/g, '').substring(0, 3).replace(/(.{3})/g, '$1')
        num_ = num_.replace(/\s/g, '').substring(3).replace(/(.{4})/g, '$1')
        this.registParam.phone = num + num_
        this.registParam.phone = (num + num_).substring(0, 13)
      },
      checkTwoPsw: function() {
        const valb = this.registParam.password
        const valc = this.registParam.passwords
        const vald = this.registParam.password.length
        const vale = this.registParam.passwords.length
        if (valb !== valc && vald > 5 && vale > 5) {
          Toast({
            message: '二次密码不一致',
            duration: 500
          })
        }
      },
      subAxios: function() {
        // 公共验证
        const that = this
        const mobile = that.registParam.phone.replace(/\s/g, '')
        const password = that.registParam.password.replace(/\s/g, '')
        const tenant_Id = that.registParam.companyName
        const toParam = {
          isOpenUp: 1,
          mobile: mobile,
          password: password,
          tenantId: tenant_Id
        }
        const check_res = that.checkParam(that.registParam)
        if (check_res) {
          that.loadingShow = true
          // console.log('toParam', toParam)
          if (that.prevent_repeat) { return }
          // that.sub_btn_msg = '注册中…'
          that.prevent_repeat = true
          // 单点注册
          AccountApi.registerDirver(toParam).then(res => {
            if (res.status === 200) {
              if (res.data.code === 0) {
                that.loadingShow = false
                const loginType = 'driver'
                this.$store.commit('SET_LOGIN_TYPE', loginType)
                this.$router.push({ name: 'signup-success', params: { toParam }})
              } else {
                that.loadingShow = false
                Toast({
                  message: res.data.message || '用户token获取失败',
                  duration: 1000
                })
                return
              }
            }
            that.prevent_repeat = false
          }).catch(error => {
            that.loadingShow = false // 如果注册失败
            that.prevent_repeat = false
            Toast({
              message: error.message || '系统繁忙，请稍候再试',
              duration: 1000
            })
          })
        }
      },
      checkParam: function(params) {
        const { phone, password, passwords, companyName } = params
        if (phone === '') {
          Toast({
            message: '请输入手机号码！',
            duration: 1000
          })
          return
        }
        if (password === '') {
          Toast({
            message: '请输入登录密码！',
            duration: 1000
          })
          return
        }
        const password_res = password.length
        if (password_res < 6 || password_res > 20) {
          Toast({
            message: '请输入6-20位密码！',
            duration: 1000
          })
          return
        }
        if (passwords === '') {
          Toast({
            message: '请输入确认密码！',
            duration: 1000
          })
          return
        }
        if (password !== passwords) {
          Toast({
            message: '二次密码不一致！',
            duration: 1000
          })
          return
        }
        const phone_res = Utils.checkMobile(phone)
        if (!phone_res) {
          Toast({
            message: '请输入有效的手机号码！',
            duration: 1000
          })
          return
        }
        if (companyName === '') {
          Toast({
            message: '请输入公司名称！',
            duration: 1000
          })
          return
        }
        return true
      },
      toLoginNormal: function() {
        this.$router.push({ name: 'signup-normal' })
      }
    }
  }
</script>

<style scoped>
  @import '../../styles/util.css';
  @import '../../styles/login_regist.css';
  .input-label.w90{
    text-align: center;
    width: .9rem;
  }
  /* input 与删除 */
  .f-fl.input-label{
    margin-right: 0;
  }
  .cell-input.w150{
    width: 1.5rem;
    overflow: hidden;
    text-overflow:ellipsis;
    white-space:nowrap;
    text-align:left;
  }
  .input-cells.a-between{
    -webkit-justify-content: space-between;
    -moz-justify-content: space-between;
    -ms-justify-content: space-between;
    -webkit-box-pack: justify;
    justify-content: space-between;
  }
  .input-cells>img{
    display: block;
    width: .32rem;
    height: .32rem;
    margin-right: 0;
    padding-right: 0.08rem;
  }
</style>
